<template>
  <div class="app-container">
    <div class="block">
      <el-row>
        <el-col :span="14" :offset="4">
          <header class="form_header">添加商品</header>
          <el-form
            :model="goodData"
            :rules="goodrules"
            ref="goodForm"
            label-width="110px"
            class="form good_form"
          >
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="goodData.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="goodData.price"></el-input>
            </el-form-item>
            <el-form-item label="商品库存" prop="num">
              <el-input v-model="goodData.num"></el-input>
            </el-form-item>
            <!--            <el-form-item label="商品活动" prop="activity">-->
            <!--              <el-input v-model="goodData.activity"></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item label="商品详情" prop="description">
              <el-input v-model="goodData.description"></el-input>
            </el-form-item>
            <el-form-item label="截止日期" prop="endTime">
              <el-date-picker
                v-model="goodData.endTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="上传商品图片">
              <el-upload
                action="#"
                :on-change="handleChange"
                :auto-upload="false"
                :on-preview="handlePreview"
                list-type="picture-card"
                :on-remove="handleRemove"
                :on-success="onSuccess">
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addGood">确认添加商品</el-button>
            </el-form-item>
          </el-form>
          <el-dialog title="添加规格" :visible.sync="dialogFormVisible">
            <el-form :rules="specsFormrules" :model="specsForm">
              <el-form-item label="规格" label-width="100px" prop="specs">
                <el-input
                  v-model="specsForm.specs"
                  auto-complete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="包装费" label-width="100px">
                <el-input-number
                  v-model="specsForm.packing_fee"
                  :min="0"
                  :max="100"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="价格" label-width="100px">
                <el-input-number
                  v-model="specsForm.price"
                  :min="0"
                  :max="10000"
                ></el-input-number>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="addspecs">确 定</el-button>
            </div>
          </el-dialog>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { addGood } from '../../api/communityHelp/goods'
import { uploadImg } from '../../api/ec/img'

export default {
  name: 'AddGood',
  data() {
    return {
      restaurant_id: 1,
      categoryForm: {
        categoryList: [
          '热销',
          '主食',
          '饮料'
        ],
        categorySelect: '',
        name: '',
        description: ''
      },
      fileMgrUrl: '/file',
      uploadHeaders: {
        Authorization: ''
      },
      goodForm: {
        name: '',
        description: '',
        image_path: '',
        activity: '',
        attributes: [],
        specs: [
          {
            specs: '默认',
            packing_fee: 0,
            price: 20
          }
        ]
      },
      categoryRules: {
        name: [{ required: true, message: '请选择商品种类', trigger: 'blur' }]
      },
      goodrules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        attributes: [
          { required: true, message: '请选择商品特点', trigger: 'blur' }
        ],
        categoryName: [
          { required: true, message: '请选择商品种类', trigger: 'blur' }
        ]
      },
      attributes: [
        {
          value: '新',
          label: '新品'
        },
        {
          value: '招牌',
          label: '招牌'
        }
      ],
      showAddCategory: false,
      goodSpecs: 'more',
      dialogFormVisible: false,
      specsForm: {
        specs: '',
        packing_fee: 0,
        price: 20
      },
      specsFormrules: {
        specs: [{ required: true, message: '请输入规格', trigger: 'blur' }]
      },
      goodData: {
        goodsId: 0,
        name: 111,
        price: 2,
        imagePath: '',
        endTime: null,
        monthSales: 0,
        totalSales: 0,
        description: '',
        rating: 5,
        state: 1,
        num: 1,
        communityId: 0,
        noticeFlag: 0
      },
      restaurantId: 0,
      imgFile: null
    }
  },
  // mounted() {
  //   this.restaurantId = this.$route.query.restaurantId
  // },
  methods: {
    handleChange(file) {
      this.imgFile = file.raw
      const form = new FormData()
      form.append('file', this.imgFile)
      uploadImg(form).then(response => {
        console.log('response')
        console.log(response)
        this.goodData.imagePath = response.data
      })
      console.log(file)
    },
    handlePreview(file) {
      console.log(file)
    },
    onSuccess(response) {
      console.log('response')
      console.log(response)
    },
    handleRemove(file) {
      console.log(file)
    },
    addGood() {
      addGood(this.goodData).then(response => {
        if (response.code === 200) {
          this.$message.success('添加成功')
        } else {
          this.$message.error('添加失败')
        }
      })
    },
    async initData() {
      try {
        const result = await getCategory(this.restaurant_id)
        if (result.code === 20000) {
          result.category_list.map((item, index) => {
            item.value = index
            item.label = item.name
          })
          this.categoryForm.categoryList = result.category_list
        } else {
          console.log(result)
        }
      } catch (err) {
        console.log(err)
      }
    },
    addCategoryFun() {
      this.showAddCategory = !this.showAddCategory
    },
    submitcategoryForm(formName) {
      console.log(this.categoryForm)
      this.$refs[formName].validate(async valid => {
        if (valid) {
          console.log(2, this.categoryForm)
          const params = {
            name: this.categoryForm.name,
            description: this.categoryForm.description,
            restaurant_id: this.restaurant_id
          }
          try {
            const result = await addCategory(params)
            if (result.code === 20000) {
              this.initData()
              this.categoryForm.name = ''
              this.categoryForm.description = ''
              this.showAddCategory = false
              this.$message({
                type: 'success',
                message: '添加成功'
              })
            }
          } catch (err) {
            console.log(err)
          }
        } else {
          this.$notify.error({
            title: '错误',
            message: '请检查输入是否正确',
            offset: 100
          })
          return false
        }
      })
    },
    uploadImg(res) {
      this.goodForm.imagePath =
        getApiUrl() + '/file/getImgStream?fileName=' + res.data.realFileName
      this.goodForm.image_path = res.data.realFileName
    },
    beforeImgUpload(file) {
      const isRightType =
        file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isRightType) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isRightType && isLt2M
    },
    addspecs() {
      this.goodForm.specs.push({ ...this.specsForm })
      this.specsForm.specs = ''
      this.specsForm.packing_fee = 0
      this.specsForm.price = 20
      this.dialogFormVisible = false
    },
    handleDelete(index) {
      this.goodForm.specs.splice(index, 1)
    },
    tableRowClassName(row, index) {
      if (index === 1) {
        return 'info-row'
      } else if (index === 3) {
        return 'positive-row'
      }
      return ''
    }
  }
}
</script>

<style scoped>
  /deep/.form {
    min-width: 400px;
    margin-bottom: 30px;
  }

  /deep/.form:hover {
    box-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6),
    0 2px 4px 0 rgba(232, 237, 250, 0.5);
    border-radius: 6px;
    transition: all 400ms;
  }

  /deep/.good_form {
    border: 1px solid #eaeefb;
    padding: 10px 10px 0;
  }

  /deep/.form_header {
    text-align: center;
    margin-bottom: 10px;
  }

  /deep/.category_select {
    border: 1px solid #eaeefb;
    padding: 10px 30px 10px 10px;
    border-top-right-radius: 6px;
    border-top-left-radius: 6px;
  }

  /deep/.add_category_row {
    height: 0;
    overflow: hidden;
    transition: all 400ms;
    background: #f9fafc;
  }

  .showEdit {
    height: 185px;
  }

  /deep/.add_category {
    background: #f9fafc;
    padding: 10px 30px 0px 10px;
    border: 1px solid #eaeefb;
    border-top: none;
  }

  /deep/.add_category_button {
    text-align: center;
    line-height: 40px;
    border-bottom-right-radius: 6px;
    border-bottom-left-radius: 6px;
    border: 1px solid #eaeefb;
    border-top: none;
    transition: all 400ms;
  }

  /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  /deep/.avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  /deep/.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  /deep/.avatar {
    width: 120px;
    height: 120px;
    display: block;
  }

  .cell {
    text-align: center;
  }
</style>


